package fun.codedesign.principle.advice151.a044;

import java.io.*;

import fun.codedesign.principle.advice151.Good;

/**
 * 推荐序列化拷贝 <br>
 * <pre>
 * </pre>
 *
 * @author zengjian
 * @create 2018-07-02 17:46
 * @since 1.0.0
 */
@Good("推荐用序列化的方式进行拷贝, 以下为一个工具类示例")
public abstract class SerializableClone {

    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T clone(T t) {
        // 读取字节到内存
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        T dest = null;
        try {
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(t);
            oos.close();
            // 分配内存空间写入原始对象
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            dest = (T) ois.readObject();
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dest;
    }
}
